﻿using System.IO;
using System.Windows;

using EnvDTE;

namespace FanaticToy.CommandCore
{
    public class CreateResourceCurrentQuick
    {
        public void Execute(DTE dte)
        {
            try
            {
                ExecuteCore(dte);
            }
            catch (System.Exception ex)
            {
                Clipboard.SetText($@"/*
{ex.Message}
*/");
            }
        }

        public void ExecuteCore(DTE dte)
        {
            var projName = GetProjectName(dte);
            var projPath = GetProjectPath(dte);
            var docPath = GetDocumentPath(dte);

            if (string.IsNullOrWhiteSpace(projName)) { Clipboard.SetText("// projName not found"); return; }
            if (string.IsNullOrWhiteSpace(projPath)) { Clipboard.SetText("// projPath not found"); return; }
            if (string.IsNullOrWhiteSpace(docPath)) { Clipboard.SetText("// docPath not found"); return; }

            var relPath = docPath.Substring(projPath.Length).Trim('/', '\\');
            var uri = $@"pack://application:,,,/{projName};component/{relPath}";
            uri = uri.Replace('\\', '/');
            Clipboard.SetText(uri);
        }

        ///<summary>获得项目所属名。</summary>
        private string GetProjectName(DTE dte)
        {
            var activeDocument = dte.ActiveDocument;
            var projItem = activeDocument.ProjectItem;
            var containingProject = projItem.ContainingProject;

            if (containingProject == null) return string.Empty;

            return containingProject.Name;
        }

        ///<summary>获得项目所属名。</summary>
        private string GetProjectPath(DTE dte)
        {
            var activeDocument = dte.ActiveDocument;
            var projItem = activeDocument.ProjectItem;
            var containingProject = projItem.ContainingProject;

            if (containingProject == null) return string.Empty;

            return Path.GetDirectoryName(containingProject.FileName);
        }

        private string GetDocumentPath(DTE dte)
        {
            var activeDocument = dte.ActiveDocument;
            return activeDocument.FullName;
        }
    }
}
